package com.test.study.shiro_demo.matcher;

import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;


public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {
    //声明缓存对象
    private Ehcache passwordRetryEhcache;
    //声明从构造方法获取缓存对象
    public RetryLimitHashedCredentialsMatcher(EhCacheManager ehCacheManager){
        passwordRetryEhcache= ehCacheManager.getCacheManager().getCache("passwordRetryCache");
    }

    //复写父类的登录认证方法
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
       //声明遍历记录次数
        int i=0;
        //1、获取用户的登录次数的缓存信息
            //获取用户的身份信息（身份信息为缓存数据的键名)
        String username=token.getPrincipal().toString();
        //获取缓存对象
        Element element=passwordRetryEhcache.get(username);
        //2、判断是否有缓存数据
        if(element==null){//没有缓存登录次数，则创建新的缓存
            Element ele=new Element(username,new AtomicInteger(0));
            passwordRetryEhcache.put(ele);
        }else {
            //有缓存直接递增
            AtomicInteger atomicInteger = (AtomicInteger) element.getObjectValue();
            //自增之后的值
            i = atomicInteger.incrementAndGet();
        }
        //3、如果不是4次进行认证登录，认证失败次数+1， 认证成功次数清空
        if (i>=4){
            throw new ExcessiveAttemptsException();
        }
        //4、进行本次请求的登录
        boolean match = super.doCredentialsMatch(token, info);
        //如果登录成功则将错误次数删除
        if(match){//登录成功
            passwordRetryEhcache.remove(username);
        }

        return match;
    }
}
